#include "googlerecaptcha.h"
#include <QRegExp>
#include <QDebug>
#include <QUrl>
#include "commonutils.h"

GoogleRecaptcha::GoogleRecaptcha(QObject *parent) :
    QObject(parent)
{
    googet=new QNetworkAccessManager();
    lastAddr=NULL;
    connect(googet, SIGNAL( finished(QNetworkReply*)),
            this, SLOT( replied(QNetworkReply*)) );

}

GoogleRecaptcha::~GoogleRecaptcha(){
    delete googet;
}

void GoogleRecaptcha::replied(QNetworkReply* rply){
    if(rply->error()!=QNetworkReply::NoError){
        qDebug()<<"Failed to retrive page"<<lastAddr->toString()<<rply->errorString()<<rply->error();
        return;
    };
    QString resp(rply->readAll());
    if(QVariant::Invalid!=rply->header(QNetworkRequest::LocationHeader)){
        QUrl url(rply->header(QNetworkRequest::LocationHeader).toUrl());
        getPage(url.toString());
        return;
    }

    QRegExp reg1("(image?[^\"]*)");
    reg1.indexIn(resp);
    QString picPath(reg1.cap(1));
    QRegExp reg2("c=(.*)");
    reg2.indexIn(picPath);

    if(picPath.length()>5){
        //picture found
        emit imageLocated((lastAddr->resolved(QUrl(picPath))).toString(), QString (reg2.cap(1)));
    }
}

void GoogleRecaptcha::getPage(QString address){
    if(lastAddr!=NULL){
        delete lastAddr;
    }
    lastAddr=new QUrl(address);

    googet->get(QNetworkRequest(*lastAddr));
};

void GoogleRecaptcha::getImgAddress(QString referer){
    QRegExp reg("(http\\:\\/\\/api\\.recaptcha\\.net\\/noscript[^\"]*)");
    reg.indexIn(referer);
    QString path;
    
    if(!referer.contains("src"))
        path = referer;
	else
		path=QString(reg.cap(1));
    if(path.length()<5){
        emit imageLocated("", "");
        return;
    };
    getPage(path);
};

QString GoogleRecaptcha::createPost(CaptchaDesc*desc){
    QString resp("action=checkcaptcha");
    resp.append("&recaptcha_challenge_field="+desc->getChallange());
    resp.append("&recaptcha_response_field="+desc->getCaption().replace(" ","+"));
    return resp;
};
